//
//  LBRegisterVC.m
//  V-Learn
//
//  Created by Apple on 2018/12/26.
//  Copyright © 2018 yxk. All rights reserved.
//

#import "LBRegisterVC.h"
#import "NSString+Category.h"
#import "YYModel.h"
#import "UserModel.h"
#import "BRAPPViewModel.h"

#import "UIButton+Category.h"
#import "UIColor+BRCategory.h"
#import "UILabel+BRFont.h"
#import "SVProgressHUD.h"
#import "UIView+BRCategory.h"
#import "LBBoundingIponeVC.h"
#import "LBReisterProtocolVC.h"

@interface LBRegisterVC ()<UITextFieldDelegate>
@property (nonatomic,strong)UIImageView * logo;

@property (nonatomic,strong)UIButton * PasswordLogin;
@property (nonatomic,strong)UIButton * NoteLogin;
@property (nonatomic,strong)UIView * LineView;

@property (nonatomic,strong)UITextField * PhoneNumTF;
@property (nonatomic,strong)UITextField * PassWordTF;
@property (nonatomic,strong)UITextField * codeTF;
//@property (nonatomic,strong)UITextField * CodeTF;
@property (nonatomic,strong)UIView * LineView2;
@property (nonatomic,strong)UIButton * WeChatLogin;
@property (nonatomic,strong)UIView * NoteLoginView;

@property (nonatomic,strong)UIButton * ShowPassWordButton;
@property (nonatomic,strong)UIButton * CleanButton;
@property (nonatomic,strong)NSString * authId;
// 0 账号密码  1 短信    2 微信
@property (nonatomic,assign)NSInteger loginType;
@property (nonatomic,copy)NSString * openID;
//@property (nonatomic,copy)LoginBlock  block;

@end

@implementation LBRegisterVC


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"注册";
    [self SetUI];
}
- (void)SetUI{
    
    self.logo = [[UIImageView alloc] init];
    [self.view addSubview:self.logo];
    [self.logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.centerX.mas_equalTo(self.view);
    }];
    self.logo.image = [UIImage imageNamed:@"logo"];

    self.PhoneNumTF = [[UITextField alloc] init];
    self.PassWordTF = [[UITextField alloc] init];
    self.codeTF = [[UITextField alloc] init];
    [self.view addSubview:self.PhoneNumTF];
    [self.view addSubview:self.PassWordTF];
    [self.view addSubview:self.codeTF];
    
    self.PhoneNumTF.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTF.keyboardType = UIKeyboardTypeDefault;
    self.PassWordTF.keyboardType = UIKeyboardTypeNumberPad;
    
    self.codeTF.secureTextEntry = YES;
    self.PhoneNumTF.placeholder = @"请输入手机号";
    self.PassWordTF.placeholder = @"请输入验证码";
    self.codeTF.placeholder = @"请输入密码";
    
    self.PhoneNumTF.clearButtonMode = UITextFieldViewModeAlways;
    self.PassWordTF.clearButtonMode = UITextFieldViewModeAlways;
    
    [self.PhoneNumTF setValue:rgb(152, 152, 152) forKeyPath:@"_placeholderLabel.textColor"];
    [self.PassWordTF setValue:rgb(152, 152, 152) forKeyPath:@"_placeholderLabel.textColor"];
    [self.codeTF setValue:rgb(152, 152, 152) forKeyPath:@"_placeholderLabel.textColor"];
    
    [self.PhoneNumTF setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [self.PassWordTF setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [self.codeTF setValue:[UIFont systemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    
    self.PassWordTF.textColor = rgb(40, 40, 40);
    self.PhoneNumTF.textColor = rgb(40, 40, 40);
    self.codeTF.textColor = rgb(40, 40, 40);
    
    [self.PhoneNumTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(15);
        make.right.equalTo(-15);
        make.top.equalTo(self.logo.mas_bottom).offset(LBSetY(70));
        make.height.mas_equalTo(45);
    }];

    
    UIView * tempLineView2 = [[UIView alloc] init];
    tempLineView2.backgroundColor = rgb(210, 210, 210);
    [self.view addSubview:tempLineView2];
    [tempLineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.PhoneNumTF);
        make.height.equalTo(@1);
        make.right.equalTo(-15);
        
        make.top.equalTo(self.PhoneNumTF.mas_bottom).offset(0);
    }];
    
    [self.PassWordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.PhoneNumTF);
        make.top.equalTo(self.PhoneNumTF.mas_bottom).offset(10);
        make.right.mas_equalTo(-125);
    }];
    
    self.PassWordTF.placeholder = @"请输入验证码";
    
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.PassWordTF);
        make.top.equalTo(self.PassWordTF.mas_bottom).offset(10);
        make.right.mas_equalTo(-53);
    }];
    self.codeTF.placeholder = @"请输入密码";

    //wk_eye
    
    UIButton *eyeBtn = [[UIButton alloc] init];
    [eyeBtn setImage:LBImage(@"wk_eye") forState:UIControlStateNormal];
    [eyeBtn setImage:LBImage(@"eye") forState:UIControlStateSelected];
    [eyeBtn setTitleColor:rgb(152, 152, 152) forState:(UIControlStateNormal)];
    [self.view addSubview:eyeBtn];
    [eyeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeTF).mas_equalTo(-3);
        make.size.mas_equalTo(CGSizeMake(40*ScaleX, 40*ScaleX));
        make.right.mas_equalTo(-10);
    }];
    
//    eyeBtn.titleLabel.isAdaptiveFont = @"";
//    eyeBtn.titleLabel.font = LBFont(14);
    eyeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [eyeBtn addTarget:self action:@selector(clickEyeBtn:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIView * tempLineView3 = [[UIView alloc] init];
    tempLineView3.backgroundColor = rgb(210, 210, 210);
    [self.view addSubview:tempLineView3];
    [tempLineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.codeTF);
        make.height.equalTo(@1);
        make.right.equalTo(-15);
        make.top.equalTo(self.codeTF.mas_bottom).offset(0);
    }];
    

    UIButton * btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
    
    [btn setTitleColor:rgb(152, 152, 152) forState:(UIControlStateNormal)];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.PassWordTF);
        make.width.mas_equalTo(120);
        make.right.mas_equalTo(-10);
    }];
    btn.titleLabel.isAdaptiveFont = @"";
    btn.titleLabel.font = LBFont(14);
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [btn addTarget:self action:@selector(getCode:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIView * lineView4 = [[UIView alloc] init];
    lineView4.backgroundColor = [UIColor colorWithHexString:@"#7d7a80"];
    [self.view addSubview:lineView4];
    
    [lineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.centerY.equalTo(btn);
        make.height.mas_equalTo(25);
        make.width.mas_equalTo(1);
    }];
    
    
    self.registerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.registerButton setTitle:@"注册" forState:(UIControlStateNormal)];
    self.registerButton.titleLabel.isAdaptiveFont = @"";
    self.registerButton.titleLabel.font = LBFont(15);
    self.registerButton.layer.cornerRadius = 22;
    self.registerButton.layer.masksToBounds = YES;
    [self.view addSubview:self.registerButton];
    [self.registerButton setBackgroundImage:LBImage(@"wk_shadow_btn") forState:(UIControlStateNormal)];
//    self.registerButton.backgroundColor = rgb(193, 83, 27);
    [self.registerButton setTitleColor:rgb(255,255,255) forState:UIControlStateNormal];
    [self.registerButton addTarget:self action:@selector(clickRegisterBtn:) forControlEvents:UIControlEventTouchUpInside];
//    self.registerButton.he_timeInterval = 2;
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(15);
        make.right.equalTo(-15);
        make.top.equalTo(tempLineView3.mas_bottom).offset(LBSetY(50));
        make.height.mas_equalTo(44);
    }];

    UIView * tempLine3 = [[UIView alloc] init];
    tempLine3.backgroundColor = tempLineView2.backgroundColor;
    [self.view addSubview:tempLine3];
    [tempLine3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(tempLineView2);
        make.top.equalTo(self.PassWordTF.mas_bottom);
    }];
    
    
    //已有账号返回登录
    UILabel * accountLabel = [[UILabel alloc] init];
    accountLabel.text = @"已有账号，去登录";
    accountLabel.isAdaptiveFont = @"";
    accountLabel.font = LBFont(13*ScaleX);
    accountLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:accountLabel];
    accountLabel.textColor = rgb(230,84,0);
    [accountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-12*ScaleX);
        make.top.mas_equalTo(self.registerButton.mas_bottom).mas_equalTo(15*ScaleX);
    }];
    
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAccount)];
    accountLabel.userInteractionEnabled = YES;
    [accountLabel addGestureRecognizer:tapG];
    
    //注册即表示同意《用户注册协议》
    UILabel * protocolLabel = [[UILabel alloc] init];
    
    NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:@"点击注册按钮表示您已同意《用户注册协议》"];
    //获取要调整颜色的文字位置,调整颜色
    NSRange range1=[[hintString string]rangeOfString:@"《用户注册协议》"];
    [hintString addAttribute:NSForegroundColorAttributeName value:rgb(233,84,18) range:range1];
    
//    NSRange range2=[[hintString string]rangeOfString:@"服务协议"];
//    [hintString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
    
    
    
//    protocolLabel.text = @"注册即表示同意《用户注册协议》";
    protocolLabel.attributedText = hintString;
    protocolLabel.isAdaptiveFont = @"";
    protocolLabel.font = LBFont(12);
    protocolLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:protocolLabel];
//    protocolLabel.textColor = rgb(101,101,101);
    [protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.bottom.mas_equalTo(-30);
    }];
    
    UITapGestureRecognizer *tapG2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickProtocol)];
    protocolLabel.userInteractionEnabled = YES;
    [protocolLabel addGestureRecognizer:tapG2];

}
#pragma mark - 跳转绑定手机页面
- (void)clickRegisterBtn:(UIButton *)sender{
    //防止按钮重复点击
    NSString *phoneNum = self.PhoneNumTF.text;//手机号
    NSString *code = self.PassWordTF.text;//验证码
    NSString *password = self.codeTF.text;//密码
    if (phoneNum.length==0||phoneNum==nil) {
        [MBProgressHUD showSuccess:@"手机号为空" toView:self.view];
        return;
    }

    if (code.length==0||code==nil) {
        [MBProgressHUD showSuccess:@"验证码为空" toView:self.view];
        return;
    }
    if (password.length==0||password==nil) {
        [MBProgressHUD showSuccess:@"密码为空" toView:self.view];
        return;
    }
    if (password.length<6||password.length>12) {
        [MBProgressHUD showSuccess:@"请输入6~12密码" toView:self.view];
        return;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:phoneNum forKey:@"tel"];
    [data setObject:password forKey:@"password"];
    [data setObject:code forKey:@"code"];
    [WYHXNetWorkManager post:WKUserRigester_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        NSString *msg = responseObj[@"msg"];
//        NSLog(@"%@",responseObj);
        
        if ([code integerValue]==200) {
            [MBProgressHUD showSuccess:@"注册成功" toView:self.view];
            NSDictionary *dict = (NSDictionary *)responseObj;
            NSDictionary *data = dict[@"data"];
            UserModel *model = [UserModel mj_objectWithKeyValues:data];
            [UserModel SaveUserModel:model];
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else{ //if([code integerValue]==500){
            [MBProgressHUD showSuccess:msg toView:self.view];
            return ;
        }
    }];

}
#pragma mark - 返回登录页面
- (void)clickAccount{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)clickProtocol{
    LBReisterProtocolVC *protocolVC = [LBReisterProtocolVC new];
    [self.navigationController pushViewController:protocolVC animated:YES];
}

- (void)clickEyeBtn:(UIButton *)btn{
    btn.selected = !btn.selected;
    self.codeTF.secureTextEntry = !btn.selected;
    
}
- (void)getCode:(UIButton *)btn{
    
//    [self openCountdown:btn];
    // 获取验证码
    if (![self.PhoneNumTF.text isMobile]) {
        [MBProgressHUD showSuccess:@"请输入正确的手机号" toView:self.view];
        return;
    }
    [self.PassWordTF becomeFirstResponder];
    NSString *iphoneNum = self.PhoneNumTF.text;
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:iphoneNum forKey:@"tel"];
    
    [WYHXNetWorkManager get:WKGetCode_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
//        NSLog(@"%@%@",responseObj,error);
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            [self openCountdown:btn];
        //
        }
    }];
    return;
    
}
// 开启倒计时效果
-(void)openCountdown:(UIButton *)btn{
    
    btn.userInteractionEnabled = NO;
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [btn setTitle:@"重新发送" forState:UIControlStateNormal];
                
                btn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [btn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                
                btn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}


@end
